using System;
using System.Web;

namespace Framework.Library.Core.Utils.Web
{
    /// <summary>
    /// A <see cref="WebParameterAttribute"/> that's specifically bound to the
    /// a parameter in the query string (Request.QueryString collection)
    /// </summary>
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public sealed class QueryParameterAttribute : WebParameterAttribute
    {
        private bool _decode;

        public bool Decode
        {
            get { return _decode; }
            set { _decode = value; }
        }

        #region Constructors

        /// <summary>
        /// Creates a new QueryParameterAttribute to load a field from an identically-named
        /// parameter in the QueryString collection, if it exists.
        /// The parameter has no default value, and is not required
        /// </summary>
        public QueryParameterAttribute()
        {
        }

        /// <summary>
        /// Creates a new QueryParameterAttribute to load a field from the given parameter
        /// in the QueryString collection, if it exists.
        /// The parameter has no default value, and is not required
        /// </summary>
        /// <param name="paramName">The key of a parameter in the QueryString collections</param>
        public QueryParameterAttribute(string paramName)
            : base(paramName)
        {
        }

        #endregion

        /// <summary>
        /// Retrieves an item from the QueryString by key
        /// </summary>
        protected override string GetValue(string paramName, HttpRequest request)
        {
            string value = request.QueryString[paramName];

            if (_decode)
                value = HttpUtility.UrlDecode(value);

            return value;
        }
    }
}